import React, { useMemo, useState } from 'react';
import { PersonalInfo } from "@/pages/account/home/user-profile/index.js";
import { useQuery } from '@tanstack/react-query';
import {
  Calendar,
  Edit,
  Eye,
  FileText,
  Filter,
  HardDrive,
  Plus,
  RefreshCw,
  Search,
  Trash2,
  User,
} from 'lucide-react';
import { Link, useSearchParams } from 'react-router-dom';
import { customerService } from "@/lib/api/services/customer-service";
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Container } from '@/components/ui/container';
import { Input } from '@/components/ui/input';
import { ResponsiveTable, ResponsiveTableCell, ResponsiveTableHead, ResponsiveTableHeader, ResponsiveTableRow, TableEmpty, TableLoading } from '@/components/ui/responsive-table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { TableBody } from '@/components/ui/table';


const CustomerListPage = () => {


    const [searchParams, setSearchParams] = useSearchParams();
    // 状态
    const [searchKeyword, setSearchKeyword] = useState(searchParams.get('q') || '');
    const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '');
    const [page, setPage] = useState(parseInt(searchParams.get('page') || '1'));
    const [pageSize] = useState(10);

    // 获取客户列表
    const {
        data: customersData,
        isLoading,
        error,
        refetch
    } = useQuery({
        queryKey: ['customers', 'list', searchKeyword, statusFilter, page, pageSize],
        queryFn: () => customerService.getList({
            keyword: searchKeyword,
            status: statusFilter,
            page,
            pageSize
        })
    });

    // 状态筛选项
    const statusOptions = useMemo(() => [
        { label: '全部状态', value: 'all'},
        { label: 'Active', value: 'active'},
        { label: 'Inactive', value: 'inactive'}
    ])

    // 更新 URL 参数
    const updateURL = (params) => {
        const newParams = new URLSearchParams(searchParams);
        Object.entries(params).forEach(([key, value]) => {
            if (value) {
                newParams.set(key, value);
            } else {
                newParams.delete(key);
            }
        });
        setSearchParams(newParams);
    };


    // 搜索处理
    const handleSearch = (value) => {
        setSearchKeyword(value);
        setPage(1);
        updateURL({ q: value, page: 1 });
    };

    // 状态筛选
    const handleStatusChange = (value) => {
        const status = value === 'All' ? '' : value;
        setStatusFilter(status);
        setPage(1);
        updateURL({ status, page: 1 });
    };


    const handleDeleteCustomer = (customer) => {
        if (confirm(`确定要删除客户"${customer.name}"吗？`)) {
            console.log('删除客户:', customer);
            // TODO: 调用删除API
        }
    };


    // 分页处理
    // const handlePageChange = (newPage) => {
    //     setPage(newPage);
    //     updateURL({ page: newPage });
    //     window.scrollTo({ top: 0, behavior: 'smooth' });
    // };
    //

    // 格式化日期
    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
    };

    const customers = customersData?.data || [];
    const meta = {
        page: customersData?.page || 1,
        pageSize: customersData?.pageSize || 10,
        total: customersData?.total || 0,
        totalPages: customersData?.totalPages || 0
    };

    return (
        <Container>
            {/* 页面标题 */}
            <div className="flex items-center justify-between mb-6">
                <div>
                    <h1 className="text-3xl font-bold">客户列表</h1>
                    <p className="text-muted-foreground mt-1">
                        共 {meta.total} 位客户
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <Link to="/documentation/new">
                        <Button>
                            <Plus className="size-4 mr-2" />
                            新建客户
                        </Button>
                    </Link>
                </div>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>客户列表</CardTitle>
                </CardHeader>

                <CardContent>
                    {/* 搜索和筛选 */}
                    <div className="flex flex-col md:flex-row gap-4 mb-6">
                        {/* 搜索框 */}
                        <div className="flex-1 relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-gray-400" />
                            <Input
                                placeholder="搜索客户名称、邮箱..."
                                value={searchKeyword}
                                onChange={(e) => handleSearch(e.target.value)}
                                className="pl-10"
                            />
                        </div>

                        {/* 状态筛选 */}
                        <Select value={statusFilter || 'all'} onValueChange={handleStatusChange}>
                            <SelectTrigger className="w-full md:w-36">
                                <Filter className="size-4 mr-2" />
                                <SelectValue placeholder="全部状态" />
                            </SelectTrigger>
                            <SelectContent>
                                {statusOptions.map(sta => (
                                    <SelectItem key={sta.value || 'all'} value={String(sta.value)}>
                                        {sta.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>

                        {/* 刷新按钮 */}
                        <Button
                            variant="outline"
                            size="icon"
                            onClick={() => refetch()}
                            title="刷新"
                        >
                            <RefreshCw className="size-4" />
                        </Button>
                    </div>

                    {/* 表格 */}
                    <ResponsiveTable>
                        <ResponsiveTableHeader>
                            <ResponsiveTableRow>
                                <ResponsiveTableHead>名称</ResponsiveTableHead>
                                <ResponsiveTableHead>邮箱</ResponsiveTableHead>
                                <ResponsiveTableHead>手机号</ResponsiveTableHead>
                                <ResponsiveTableHead hideOnMobile>创建时间</ResponsiveTableHead>
                                <ResponsiveTableHead hideOnMobile>创建人</ResponsiveTableHead>
                                <ResponsiveTableHead hideOnMobile>更新时间</ResponsiveTableHead>
                                <ResponsiveTableHead hideOnMobile>更新人</ResponsiveTableHead>
                                <ResponsiveTableHead>状态</ResponsiveTableHead>
                                <ResponsiveTableHead>操作</ResponsiveTableHead>
                            </ResponsiveTableRow>
                        </ResponsiveTableHeader>
                        <TableBody>
                            {isLoading ? (
                                <TableLoading colSpan={9} />
                            ):(
                                customers.map((customer) => (
                                    <ResponsiveTableRow key={customer.id}>
                                        {/* 名称 */}
                                        <ResponsiveTableCell className="font-medium">
                                            <Link
                                                to={`/customer/${customer.id}`}
                                                className="hover:text-primary transition-colors flex items-center gap-2"
                                            >
                                                <span className="line-clamp-1">{customer.name}</span>
                                            </Link>
                                        </ResponsiveTableCell>
                                        {/* 邮箱 */}
                                        <ResponsiveTableCell>
                                            <span className="line-clamp-1">{customer.email}</span>
                                        </ResponsiveTableCell>
                                        {/* 手机号 */}
                                        <ResponsiveTableCell>
                                            <span className="line-clamp-1">{customer.phone}</span>
                                        </ResponsiveTableCell>
                                        {/* 创建时间 */}
                                        <ResponsiveTableCell hideOnMobile>
                                            <div className="flex items-center gap-2 text-sm text-gray-600">
                                                <Calendar className="size-3" />
                                                {formatDate(customer.createdAt)}
                                            </div>
                                        </ResponsiveTableCell>
                                        {/* 创建人 */}
                                        <ResponsiveTableCell hideOnMobile>
                                            <div className="flex items-center gap-2 text-sm text-gray-600">
                                                <User className="size-3 text-gray-400" />
                                                {customer.createdBy}
                                            </div>
                                        </ResponsiveTableCell>
                                        {/* 更新时间 */}
                                        <ResponsiveTableCell hideOnMobile>
                                            <div className="flex items-center gap-2 text-sm text-gray-600">
                                                <Calendar className="size-3" />
                                                {formatDate(customer.updatedAt)}
                                            </div>
                                        </ResponsiveTableCell>
                                        {/* 更新人 */}
                                        <ResponsiveTableCell hideOnMobile>
                                            <div className="flex items-center gap-2 text-sm text-gray-600">
                                                <User className="size-3 text-gray-400" />
                                                {customer.updatedBy}
                                            </div>
                                        </ResponsiveTableCell>

                                        {/* 状态 */}
                                        <ResponsiveTableCell>
                                            <div className="flex items-center gap-2 text-sm text-gray-600">
                                                {/*<Badge*/}
                                                {/*    variant={customer.status === 'active' ? 'default' : 'warning'}*/}
                                                {/*    className="text-xs"*/}
                                                {/*>*/}
                                                    {customer.status === 'active' ? '正常' : '禁用'}
                                                {/*</Badge>*/}
                                            </div>
                                        </ResponsiveTableCell>
                                        {/* 操作 */}
                                        <ResponsiveTableCell>
                                            <div className="flex items-center gap-2">
                                                <Link to={`/customer/${customer.id}`}>
                                                    {/*<Button variant="primary" size="sm">*/}
                                                        <Edit className="size-3" xlinkTitle={'编辑'}/>
                                                    {/*</Button>*/}
                                                </Link>

                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => handleDeleteCustomer && handleDeleteCustomer(customer)}
                                                    className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                                                >
                                                    <Trash2 className="size-3"  />
                                                </Button>
                                            </div>
                                        </ResponsiveTableCell>
                                    </ResponsiveTableRow>
                                ))
                            )}
                        </TableBody>
                    </ResponsiveTable>
                </CardContent>

            </Card>
        </Container>
    );
};

export default CustomerListPage;